<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约日期" prop="appointmentDate">
        <el-date-picker clearable v-model="queryParams.appointmentDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预约日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择预约状态" clearable>
          <el-option v-for="dict in appointment_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:doctorAppointment:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:doctorAppointment:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:doctorAppointment:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:doctorAppointment:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doctorAppointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="预约记录ID" align="center" prop="id" /> -->
      <el-table-column label="就诊人姓名" align="center">
        <template #default="scope">
          <span>{{ getPatientName(scope.row.patientsId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊人手机号" align="center">
        <template #default="scope">
          <span>{{ getPatientPhone(scope.row.patientsId) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="用户名" align="center">
        <template #default="scope">
          <span>{{ getUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="预约日期" align="center" prop="appointmentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" />
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="appointment_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
          v-if = "scope.row.status == 0"
           link type="primary" icon="Check"
           @click="confirmArrival(scope.row)">确认到诊</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:doctorAppointment:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:doctorAppointment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改医生预约管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="doctorAppointmentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in appointment_status" :key="dict.value"
              :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DoctorAppointment">
import { listDoctorAppointment, getDoctorAppointment, delDoctorAppointment, addDoctorAppointment, updateDoctorAppointment } from "@/api/manage/doctorAppointment";
import { ElMessageBox } from 'element-plus';
import { listUser } from "@/api/system/user"; // 假设的获取用户信息的 API
import { listPatients } from "@/api/manage/patients"; // 假设的获取病人信息的 API

const { proxy } = getCurrentInstance();
const { appointment_status } = proxy.useDict('appointment_status');


const doctorAppointmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userMap = ref({}); // 用于存储用户 ID 到姓名的映射
const patientMap = ref({}); // 用于存储就诊人 ID 到姓名的映射
const userList = ref([]); // 存储所有用户信息
const patientList = ref([]); // 存储所有病人信息
const patientPhoneMap = ref([]); // 用于存储病人的手机号

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    patientsId: null,
    userId: null,
    appointmentDate: null,
    appointmentTime: null,
    status: null,
    createTime: null,
    updateTime: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询医生预约管理列表 */
async function getList() {
  loading.value = true;
  // 获取用户信息并构建映射
  const userResponse = await listUser();
  userList.value = userResponse.rows;
  if (userList.value && userList.value.length > 0) {
    userList.value.forEach(user => {
      userMap.value[user.userId] = user.nickName; // 假设用户表中有 userId 和 nickName 字段
    });
  }

  // 获取病人信息并构建映射
  const patientResponse = await listPatients();
  console.log(patientResponse);
  patientList.value = patientResponse.rows;
  if (patientList.value && patientList.value.length > 0) {
    patientList.value.forEach(patient => {
      patientMap.value[patient.id] = patient.name; // 假设病人表中有 patientsId 和 name 字段
      patientPhoneMap.value[patient.id] = patient.contactPhone;
    });
  }

  listDoctorAppointment(queryParams.value).then(response => {
    doctorAppointmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientsId: null,
    userId: null,
    appointmentDate: null,
    appointmentTime: null,
    status: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("doctorAppointmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加医生预约管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDoctorAppointment(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改医生预约管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["doctorAppointmentRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDoctorAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDoctorAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除医生预约管理编号为"' + _ids + '"的数据项？').then(function () {
    return delDoctorAppointment(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/doctorAppointment/export', {
    ...queryParams.value
  }, `doctorAppointment_${new Date().getTime()}.xlsx`)
}

// 确认到诊的方法
const confirmArrival = async (row) => {
  try {
    // 弹出确认提示框，使用 ElMessageBox
    await ElMessageBox.confirm('是否确定用户已到诊？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 创建一个新的对象，包含要更新的字段
    const updatedData = {
      ...row,
      status: 1 // 将状态设置为 1
    };
    // 调用更新接口
    await updateDoctorAppointment(updatedData);
    // 更新本地数据
    const index = doctorAppointmentList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      doctorAppointmentList.value[index] = updatedData;
    }
    // 提示信息，告知用户操作成功
    proxy.$message.success('确认到诊成功');
  } catch (error) {
    if (error.name === 'CancelError') {
      // 用户点击了取消按钮
      console.log('用户取消了确认到诊操作');
    } else {
      console.error('确认到诊失败:', error);
      proxy.$message.error('确认到诊失败，请稍后重试');
    }
  }
};

// 获取用户姓名的函数
function getUserName(userId) {
  return userMap.value[userId] || '未知';
}

// 获取就诊人姓名的函数
function getPatientName(patientsId) {
  return patientMap.value[patientsId] || '未知';
}

// 获取就诊人手机号的函数
function getPatientPhone(patientsId) {
  return patientPhoneMap.value[patientsId] || '未知';
}

getList();
</script>
